package com.hl.sfzy.controller;

import com.hl.sfzy.entity.Request;
import com.hl.sfzy.entity.SystemUser;
import com.hl.sfzy.service.SystemUserService;
import com.hl.sfzy.utils.MD5Util;
import com.hl.sfzy.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/systemUser")
public class SystemUserController {
    @Autowired
    private SystemUserService systemUserService;
    @PostMapping("/add")
    public R add(@RequestBody SystemUser systemUser){
        int i = systemUserService.add(systemUser);
        if(i>0){
            return R.ok("添加成功");
        }else {
            return R.fail("添加失败");
        }
    }
    @GetMapping("/{id}")
    public R findById(@PathVariable Long id){
        SystemUser systemUser = systemUserService.findById(id);
        return R.ok(systemUser);
    }
    @PutMapping("/edit")
    public R edit(@RequestBody SystemUser systemUser){
        int i = systemUserService.edit(systemUser);
        if(i>0){
            return R.ok("修改成功");
        }else {
            return R.fail("修改失败");
        }
    }
    @DeleteMapping("/{id}")
    public R remove(@PathVariable Long id){
        int i = systemUserService.remove(id);
        if(i>0){
            return R.ok("删除成功");
        }else {
            return R.fail("删除失败");
        }
    }
    @GetMapping("/login")
    public R login(
            @RequestParam(value = "userName") String username,
            String password){
        SystemUser systemUser = systemUserService.login(username, password);
        if(systemUser!=null){
            return R.ok(systemUser);
        }else {
            return R.fail("登录失败 用户名或密码错误");
        }
    }

//    修改密码
    @PutMapping("/updatePassword")
    public R updatePassword(@RequestBody Request request) {
        Long passwordId = request.getPasswordId();
        String oldPassword = request.getOldPassword();
        String newPassword = request.getNewPassword();
        SystemUser systemUser = systemUserService.findById(passwordId);
//        查的用户
        System.out.println(systemUser);

        if (systemUser != null) {
            if (systemUser.getSystemUserPassword().equalsIgnoreCase(MD5Util.encode(systemUser.getSystemUserUsername()+oldPassword)))
            {
                systemUser.setSystemUserPassword(MD5Util.encode(systemUser.getSystemUserUsername()+newPassword));
                int i = systemUserService.edit(systemUser);
                if (i > 0) {
                    return R.ok("修改成功");

                } else {
                    return R.fail("修改失败");
                }
            } else {

                return R.fail("旧密码错误");
            }
        }else {
            return R.fail("用户不存在");
        }



    }


}
